<?php


namespace App\Http\Controllers\Api;

use App\Services\Other\Interfaces\SearchRecordServiceInterface;
use App\Services\Business\Models\SearchKeywords;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;


class SearchController extends BaseController
{

    protected $searchRecordService;

    public function __construct(SearchRecordServiceInterface $searchRecordService)
    {
        $this->searchRecordService = $searchRecordService;
    }

    /**
     * @api {get} /api/v2/search 录播课程搜索
     * @apiGroup 搜索
     * @apiVersion v2.0.0
     *
     * @apiParam {String} keywords 搜索关键字
     * @apiParam {Number} size 每页数量
     * @apiParam {Number} page 页码
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data
     * @apiSuccess {Number} data.id 课程ID
     * @apiSuccess {String} data.title 课程名
     * @apiSuccess {String} data.thumb 封面
     * @apiSuccess {Number} data.charge 价格
     * @apiSuccess {String} data.short_description 简短介绍
     * @apiSuccess {String} data.render_desc 详细介绍
     * @apiSuccess {String} data.seo_keywords SEO关键字
     * @apiSuccess {String} data.seo_description SEO描述
     * @apiSuccess {Number} data.is_rec 推荐[1:是,0否][已弃用]
     * @apiSuccess {Number} data.user_count 订阅人数
     * @apiSuccess {Number} data.videos_count 视频数
     * @apiSuccess {Object} data.category 分类
     * @apiSuccess {Number} data.category.id 分类ID
     * @apiSuccess {String} data.category.name 分类名
     */
    public function index(Request $request)
    {

        $type = $request->input('type','');
        $companyId = $request->input('company_id',0);
        $page = abs((int)$request->input('page'));
        $size = abs((int)$request->input('size', 10));
        $keywords = $request->input('keywords', '');
        $data = $this->searchRecordService->search($keywords,$companyId,$page, $size, $type);
        if($this->check()){
            //更新最近查询
            $userId = $this->id();
            if (!SearchKeywords::query()->where('name',$keywords)->whereUserId($userId)->exists()){
                if (SearchKeywords::query()->whereUserId($userId)->count() > 10){
                    $latestRecord = SearchKeywords::latest()->first();
                    $latestRecord->delete();
                }
                SearchKeywords::create([
                    'user_id'=>$userId,
                    'name'=>$keywords
                ]);
            }


        }
        if ($data['data']) {
            foreach ($data['data'] as $key => $item) {
                $p = '';
                $shortDesc = $item['short_desc'];
                $desc = strip_tags($item['desc']);
                if (mb_stripos($shortDesc, $keywords) !== false) {
                    $p = $shortDesc;
                } elseif (($index = mb_stripos($desc, $keywords)) !== false) {
                    // 关键字左边的字符串截取
                    if ($index < 100) {
                        $leftStr = mb_substr($desc, 0, $index);
                    } else {
                        $leftStr = mb_substr($desc, $index - 100, 100);
                    }

                    // 关键字右边的字符串截取
                    $rightStr = mb_substr($desc, $index + mb_strlen($keywords), 100) . '...';

                    $p = $leftStr . $keywords . $rightStr;
                }
                $data['data'][$key]['p'] = $p;
            }
        }
        $data['data']= collect($data['data'])->groupBy('resource_type');

        return $this->data($data);

    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public  function keyword(Request $request)
    {
        $keyword = $request->input('keywords','');
        $keywords =  SearchKeywords::query()
            ->when($keyword, function ($query) use ($keyword) {
                return $query->where('name', 'like', '%' . $keyword . '%');
            })
            ->take(10)
            ->get();
        return $this->successData(compact('keywords'));


    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function latest(Request $request)
    {

        $userId = Auth::id();
        $keywords =  SearchKeywords::query()
            ->when($userId, function ($query) use ($userId) {
                return $query->whereUserId($userId);
            })
            ->orderByDesc('created_at')
            ->take(10)->get();
        return $this->successData(compact('keywords'));

    }

    public  function delete(Request $request){

        $userId  =  Auth::id();
        $ids = $request->input('ids',[]);
        if (!$ids){
            return $this->error(__('参数错误'));
        }
        SearchKeywords::query()->where('user_id',$userId)->whereIn('id',$ids)->delete();
        return  $this->success(__('清除关键字成功'));


    }






}